package main

import (
	"Demo/btc4/ripemd"
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"fmt"
	"log"
)

type Wallet struct {
	Private *ecdsa.PrivateKey
	PubKey  []byte
}

func NewWallet() *Wallet {
	curve := elliptic.P256()
	privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err != nil {
		log.Panic()
	}
	pubKeyOrig := privateKey.PublicKey
	pubKey := append(pubKeyOrig.X.Bytes(), pubKeyOrig.Y.Bytes()...)
	return &Wallet{Private: privateKey, PubKey: pubKey}
}

func (w *Wallet) NewAddress() string {
	var address = ""
	pubKey := w.PubKey
	hash := sha256.Sum256(pubKey)
	//理解为编码器
	rip160hasher := ripemd.New()
	_, err := rip160hasher.Write(hash[:])
	if err != nil {
		log.Panic(err)
	}
	//返回rip160的哈希结果
	rip160HashValue := rip160hasher.Sum(nil)

	version := byte(00)
	payload := append([]byte{version}, rip160HashValue...)

	//返回checkCode
	hash1 := sha256.Sum256(payload)
	hash2 := sha256.Sum256(hash1[:])
	checkCode := hash2[:4]

	//返回payload
	base58 := append(payload, checkCode...)

	//生成address
	address = string(Base58Encode(base58))
	return address
}

func IsValidAddress(address string) bool {
	addressByte := Base58Decode([]byte(address))
	if len(addressByte) < 4 {
		return false
	}
	payload := addressByte[:len(addressByte)-4]
	checksum1 := addressByte[len(addressByte)-4:]
	checksum2 := CheckSum(payload)
	fmt.Printf("checksum1:%x\n", checksum1)
	fmt.Printf("checksum2:%x\n", checksum2)
	return bytes.Equal(checksum1, checksum2)
}

func CheckSum(payload []byte) []byte {
	playload := ""
	fmt.Println(playload)
	return []byte(playload)
}
